import React, {
  ReactElement,
  useRef,
  useEffect,
  useImperativeHandle,
  forwardRef
} from 'react';
import {
  View,
  Text,
  TextInput,
  Keyboard,
  TouchableOpacity
} from 'react-native';

import styles from './style';
import { InputVerifyCodeProp } from './types';

const InputVerifyCode = (
  props: InputVerifyCodeProp,
  ref: any
): ReactElement => {
  const { value, setValue } = props;

  const textInput = useRef<TextInput>(null);
  const array = new Array(4).fill('');

  useEffect((): (() => void) => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      (): void => { }
    );
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      (): void => {
        if (textInput.current) {
          textInput.current.blur();
        }
      }
    );

    return (): void => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);

  const showValues = value.split('');

  useImperativeHandle(ref, (): { [key: string]: any } => {
    return {
      focus: (): void => {
        if (textInput.current) {
          textInput.current.focus();
        }
      }
    };
  });

  return (
    <View style={styles.container}>
      <View style={styles.textInputContainer}>
        {array.map(
          (item, index): ReactElement => {
            return (
              <TouchableOpacity
                style={styles.loadValue}
                activeOpacity={0.8}
                onPress={(): void => {
                  if (textInput.current) {
                    textInput.current.focus();
                  }
                }}
              >
                {showValues[index] && (
                  <Text style={styles.letter}>{showValues[index]}</Text>
                )}
              </TouchableOpacity>
            );
          }
        )}
      </View>
      <TextInput
        ref={textInput}

        style={styles.textInput}
        keyboardType="numeric"
        maxLength={4}
        selectionColor="transparent"
        value={value}
        onChangeText={(str): void => {
          const text = str.replace(/[^0-9]/gi, '');
          setValue(text);
          // 应该加载setValue里面，满4位后还需要直接请求接口
          if (text.length === 4) {
            Keyboard.dismiss();
          }
        }}
      />
    </View>
  );
};

export default forwardRef(InputVerifyCode);
